package eerbaar.shared.internal.tree.policy;

import java.util.ArrayList;
import java.util.List;

import eerbaar.shared.tree.INode;
import eerbaar.shared.tree.IPayload;
import eerbaar.shared.tree.NodeCmdFactory;
import eerbaar.shared.tree.policy.IPolicy;

public class UniquePolicy implements IPolicy {

    @Override
    public void afterChildrenHaveChanged(INode node) {
        removeOldNodes(node);
    }

    private void removeOldNodes(INode node) {

        List<INode> list = new ArrayList<INode>();
        List<IPayload> unique = new ArrayList<IPayload>();
        INode[] children = node.getChildren();
        for (INode child : children) {

            if (unique.contains(child.getPayload())) {
                list.add(child);
            } else {
                unique.add(child.getPayload());
            }
        }

        if (list.size() > 0) {
            NodeCmdFactory.remove(node, list);
        }
    }

    @Override
    public String toString() {
        return "size node policy";
    }

}
